/**
 * 表单验证工具
 * 提供统一的验证规则和方法
 */

/**
 * 验证规则
 */
export const VALIDATION_RULES = {
  // 必填验证
  required: (value, message = '此字段为必填项') => {
    if (!value || (typeof value === 'string' && !value.trim())) {
      return message;
    }
    return null;
  },

  // URL验证（支持域名和IP地址）
  url: (value, message = '请输入有效的URL地址') => {
    if (!value) return null;
    
    // 域名格式验证
    const domainPattern = /^(https?:\/\/)([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/;
    
    // IP地址格式验证（支持IPv4和端口号）
    const ipPattern = /^(https?:\/\/)((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?::([0-9]{1,5}))?([\/\w \.-]*)*\/?$/;
    
    // localhost验证
    const localhostPattern = /^(https?:\/\/)(localhost)(?::([0-9]{1,5}))?([\/\w \.-]*)*\/?$/;
    
    if (!domainPattern.test(value) && !ipPattern.test(value) && !localhostPattern.test(value)) {
      return message;
    }
    return null;
  },

  // 长度验证
  length: (min, max, message) => (value) => {
    if (!value) return null;
    
    const length = value.toString().length;
    if (length < min || length > max) {
      return message || `长度应在${min}-${max}个字符之间`;
    }
    return null;
  },

  // 最小长度验证
  minLength: (min, message) => (value) => {
    if (!value) return null;
    
    if (value.toString().length < min) {
      return message || `最少需要${min}个字符`;
    }
    return null;
  },

  // 最大长度验证
  maxLength: (max, message) => (value) => {
    if (!value) return null;
    
    if (value.toString().length > max) {
      return message || `最多允许${max}个字符`;
    }
    return null;
  },

  // 文件类型验证
  fileType: (allowedTypes, message) => (file) => {
    if (!file) return null;
    
    const fileType = file.type;
    if (!allowedTypes.includes(fileType)) {
      return message || `只支持${allowedTypes.join(', ')}格式的文件`;
    }
    return null;
  },

  // 文件大小验证
  fileSize: (maxSize, message) => (file) => {
    if (!file) return null;
    
    if (file.size > maxSize) {
      const maxSizeMB = (maxSize / 1024 / 1024).toFixed(1);
      return message || `文件大小不能超过${maxSizeMB}MB`;
    }
    return null;
  }
};

/**
 * 导航站点验证规则
 */
export const NAVIGATION_VALIDATION = {
  name: [
    VALIDATION_RULES.required,
    VALIDATION_RULES.maxLength(50, '站点名称不能超过50个字符')
  ],
  
  description: [
    VALIDATION_RULES.maxLength(200, '描述不能超过200个字符')
  ],
  
  url: [
    VALIDATION_RULES.required,
    VALIDATION_RULES.url
  ],
  
  icon: [
    VALIDATION_RULES.fileType(
      ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'],
      '只支持 JPG、PNG、GIF、WebP 格式的图片'
    ),
    VALIDATION_RULES.fileSize(
      5 * 1024 * 1024, // 5MB
      '图片大小不能超过5MB'
    )
  ]
};

/**
 * 验证单个字段
 * @param {any} value - 要验证的值
 * @param {Array} rules - 验证规则数组
 * @returns {string|null} 错误消息或null
 */
export const validateField = (value, rules = []) => {
  for (const rule of rules) {
    const error = rule(value);
    if (error) {
      return error;
    }
  }
  return null;
};

/**
 * 验证表单对象
 * @param {Object} formData - 表单数据
 * @param {Object} validationRules - 验证规则对象
 * @returns {Object} 验证结果 { isValid: boolean, errors: Object }
 */
export const validateForm = (formData, validationRules) => {
  const errors = {};
  let isValid = true;

  for (const [field, rules] of Object.entries(validationRules)) {
    const error = validateField(formData[field], rules);
    if (error) {
      errors[field] = error;
      isValid = false;
    }
  }

  return { isValid, errors };
};

/**
 * 验证导航站点表单
 * @param {Object} navigationData - 导航站点数据
 * @returns {Object} 验证结果
 */
export const validateNavigation = (navigationData) => {
  return validateForm(navigationData, NAVIGATION_VALIDATION);
};

/**
 * 格式化URL（添加协议前缀）
 * @param {string} url - 原始URL
 * @returns {string} 格式化后的URL
 */
export const formatUrl = (url) => {
  if (!url) return '';
  
  const trimmedUrl = url.trim();
  if (!/^https?:\/\//i.test(trimmedUrl)) {
    return `https://${trimmedUrl}`;
  }
  
  return trimmedUrl;
};

/**
 * 清理表单数据
 * @param {Object} formData - 表单数据
 * @returns {Object} 清理后的表单数据
 */
export const sanitizeFormData = (formData) => {
  const sanitized = {};
  
  for (const [key, value] of Object.entries(formData)) {
    if (typeof value === 'string') {
      sanitized[key] = value.trim();
    } else {
      sanitized[key] = value;
    }
  }
  
  // 格式化URL
  if (sanitized.url) {
    sanitized.url = formatUrl(sanitized.url);
  }
  
  return sanitized;
};